var express = require('express')
var bodyParser = require('body-parser') // post解析
var fs = require('fs')
var sever = express()

sever.use(bodyParser.urlencoded({ extended: false }))
sever.use(bodyParser.json())

// 列表
sever.get('/list', function (req, res) {
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  res.setHeader("Access-Control-Allow-Origin", "*");
  fs.readFile('./db.json', 'utf8', function (err, data) {
    var data111 = JSON.parse(data).students
    console.log('读文件的data为: ', data111)
    res.end(JSON.stringify(data111))
  })
})

// 新增
sever.post('/postURL', function (req, res) {
  // 读文件
  fs.readFile('./db.json', 'utf8', function (err, data) {
    if (err) {
      console.log('读文件出错了===', err)
    }
    var comment = req.body
    console.log('comment===', comment)
    comment.id = Date.now()
    var data111 = JSON.parse(data).students
    console.log('db.json数据为1===', data111)
    data111.unshift(comment)
    console.log('db.json数据为2===', data111)
    // 写文件
    writeFile(data111)
  })
  res.end()
})

// 删除
sever.post('/delete', function (req, res) {
  fs.readFile('./db.json', 'utf8', function (err, data) {
    var data111 = JSON.parse(data).students
    var deleteId = req.body.id
    data111 = data111.filter(item => item.id !== deleteId)
    writeFile(data111)
  })
  res.end()
})

// 修改
sever.post('/update', function (req, res) {
  fs.readFile('./db.json', 'utf8', function (err, data) {
    var data111 = JSON.parse(data).students
    var updateId = req.body.id
    data111 = data111.map(item => item.id === updateId ? req.body : item)
    writeFile(data111)
  })
  res.end()
})

// 根据id查找
sever.get('/check', function (req, res) {
  console.log('req.query的类型是=======', typeof req.query)
  fs.readFile('./db.json', 'utf8', function (err, data) {
    var data111 = JSON.parse(data).students

    if (req.query.name) {
      console.log('有传参')
      const arr = []
      data111.forEach(item => {
        if (item.name === req.query.name) {
          arr.push(item)
        }
      })
      res.end(JSON.stringify(arr))
    } else {
      console.log('没传参')
      res.end(JSON.stringify(data111))
    }
  })
})

function writeFile(params) {
  var aaa = JSON.stringify({ students: params })
  fs.writeFile('./db.json', aaa, function (err) {
    if (err) {
      console.log('文件写入失败')
    } else {
      console.log('文件写入成功')
    }
  })
}

sever.listen(4000, function () {
  console.log('sever is running at port 4000')
})

